<?php
/**
 * Created by PhpStorm.
 * User: Vlad
 * Date: 2/12/14
 * Time: 7:57 PM
 */

class DB
{
    private static $db;

    public static function Connect()
    {

        if (!self::$db)
        {
            self::$db = new mysqli('localhost', 'vlad', '0FyMMGbAd7OvjivP', 'vlad');

            if ($err = mysqli_connect_errno())
            {
                echo 'Could not connect to SQL Database. Please try again later.<br />Error code: ' . $err;
                return false;
            }
            else
            {
                // delete all games older than Constants::MinutesToDeleteInactiveGamesAfter
                // count those that weren't finished

                $minutes = Constants::MinutesToDeleteInactiveGamesAfter;
                self::Query("      delete from
                                            Games
                            where
                                            LastActivity < now() - interval $minutes minute and
                                            PlayedObject is null");

                Statistics::UpdateStat(StatType::DroppedGames, self::AffectedRows());

                self::Query("      delete from
                                            Games
                            where
                                            LastActivity < now() - interval $minutes minute");
            }
        }

        return true;
    }

    public static function Disconnect()
    {
        if (self::$db)
        {
            // cleanup

            self::$db->close();
        }
    }

    public static function Prepare($query)
    {
        $stmt = self::$db->prepare($query);
        if (!$stmt)
            echo 'Error preparing SQL query: ' . self::$db->error;
        return $stmt;
    }

    public static function Query($cmd)
    {
        $res = self::$db->query($cmd);
        if (!$res)
            echo 'Error executing SQL query: ' . self::$db->error;
        return $res;
    }

    public static function AffectedRows()
    {
        return self::$db->affected_rows;
    }

    public static function LastInserted()
    {
        return self::$db->insert_id;
    }
}
